package com.example.defineview.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.example.defineview.R;

public class InputNumberView extends RelativeLayout {

    private int currentNumber=0;
    private View minusBtn;
    private EditText valueEdt;
    private View plusBtn;
    private OnNumberValueChangeListener mOnNumberValueChangeListener=null;

    public int getNumber() {
        return currentNumber;
    }

    public void setNumber(int value) {
        this.currentNumber = value;
        this.updateText();

    }

    public InputNumberView(Context context) {
        this(context,null);
    }

    public InputNumberView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public InputNumberView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //统一处理入口
        initView(context);

        setUpEvent();
    }

    private void setUpEvent() {
        minusBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                currentNumber--;
                updateText();
            }
        });

        plusBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                currentNumber++;
                updateText();
            }
        });
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.input_number_view,this);
        minusBtn = findViewById(R.id.minus_btn);
        valueEdt = findViewById(R.id.value_edit);
        plusBtn = findViewById(R.id.plus_btn);

    }

    private void updateText(){
        valueEdt.setText(String.valueOf(currentNumber));
        if (mOnNumberValueChangeListener != null) {
            mOnNumberValueChangeListener.onNumberChange(currentNumber);
        }
    }

    public void setOnNumberValueChangeListener(OnNumberValueChangeListener listener){
        this.mOnNumberValueChangeListener=listener;
    }

    public interface OnNumberValueChangeListener{
        void onNumberChange(int value);
    }
}
